package top.pmwly.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import top.pmwly.filter.JwtAuthenticationTokenFilter;
import top.pmwly.handler.RestAuthorizationEntryPoint;
import top.pmwly.handler.RestfulAccessDeniedHandler;

import javax.annotation.Resource;

/**
 * @author Herther
 * @version 1.0.0
 * @ClassName SpringSecurity.java
 * @Description springSecurity配置类
 * @createTime 2021年09月21日 12:08:00
 */
@Configuration
public class SpringSecurity extends WebSecurityConfigurerAdapter {


    /**
     * 注入自定义的UserDetailsService 认证逻辑
     */
    @Autowired
    private UserDetailsService userDetailsService;


    /**
     * jwt过滤器
     */
    @Resource
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;
    /**
     * 当未登录，或者token失效，访问接口的自定义返回结果
     */
    @Resource
    private RestAuthorizationEntryPoint restAuthorizationEntryPoint;
    /**
     * 当访问接口没有权限时自定义返回结果
     */
    @Resource
    private RestfulAccessDeniedHandler restfulAccessDeniedHandler;



    /**
     * Security 配置
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        /**
         * anyRequest          |   匹配所有请求路径
         * access              |   SpringEl表达式结果为true时可以访问
         * anonymous           |   匿名可以访问
         * denyAll             |   用户不能访问
         * fullyAuthenticated  |   用户完全认证可以访问（非remember-me下自动登录）
         * hasAnyAuthority     |   如果有参数，参数表示权限，则其中任何一个权限可以访问
         * hasAnyRole          |   如果有参数，参数表示角色，则其中任何一个角色可以访问
         * hasAuthority        |   如果有参数，参数表示权限，则其权限可以访问
         * hasIpAddress        |   如果有参数，参数表示IP地址，如果用户IP和参数匹配，则可以访问
         * hasRole             |   如果有参数，参数表示角色，则其角色可以访问
         * permitAll           |   用户可以任意访问
         * rememberMe          |   允许通过remember-me登录的用户访问
         * authenticated       |   用户登录后可访问
         */

        http.cors()
                .and()
                .csrf()
                //关闭csrf防护
                .disable()
                //关闭Session 因为使用了token
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                //过滤请求
                .authorizeRequests()
                //.antMatchers("/user/login","/user/logout")
                //.permitAll()
                //除了上面的 两个url不需要认证，其他的都需要认证
                .anyRequest()
                .authenticated()
                .and()
                //禁用缓存
                .headers()
                .cacheControl()
                .disable();

        //JWT拦截器 登录授权过滤器
        http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
        //自定义未授权和未登录 结果返回处理器
        http.exceptionHandling()
                .accessDeniedHandler(restfulAccessDeniedHandler)
                .authenticationEntryPoint(restAuthorizationEntryPoint);

    }



    /**
     * 放行swagger2 允许匿名访问
     * @param web
     * @throws Exception
     */
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers(
                //允许所有人访问knife4j
                "/v2/**",
                "/swagger-resources/**",
                "/webjars/**",
                "/doc.html",
                //登录放行
                "/user/login",
                "/user/logout"

        );
        //web.ignoring().antMatchers(HttpMethod.OPTIONS,"/**");
    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    /**
     * 重写userdteailsService 需要重写配置
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //配置配置认证逻辑 密码匹配的算法
        auth.userDetailsService(userDetailsService)
                //密码匹配的算法
                .passwordEncoder(passwordEncoder());
    }


}
